package comp.wxapi.service;
import comp.wxapi.vo.*;

import comp.wxapi.entity.*;

import org.springframework.data.domain.Page;

import java.util.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.net.URLCodec;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.binarywang.wxpay.bean.result.WxPaySendRedpackResult;
import com.github.binarywang.wxpay.config.WxPayConfig;

import comp.wxapi.bean.BaseConfigBean;
import comp.wxapi.bean.Result;
import comp.wxapi.constants.Constants;
import comp.wxapi.entity.WxQrcode;
import comp.wxapi.repository.WxQrcodeRepository;
import comp.wxapi.utils.StorageServiceUtils;
import comp.wxapi.vo.MaterialVo;
import me.chanjar.weixin.common.bean.WxCardApiSignature;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.mp.api.WxMpKefuService;
import me.chanjar.weixin.mp.api.WxMpMenuService;
import me.chanjar.weixin.mp.api.WxMpQrcodeService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.api.impl.WxMpKefuServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxMpMenuServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxMpQrcodeServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxMpTemplateMsgServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxMpUserServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.menu.WxMpGetSelfMenuInfoResult;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import weixin.popular.api.MaterialAPI;
import weixin.popular.api.MediaAPI;
import weixin.popular.bean.BaseResult;
import weixin.popular.bean.material.Description;
import weixin.popular.bean.material.MaterialBatchgetResult;
import weixin.popular.bean.material.MaterialGetResult;
import weixin.popular.bean.material.MaterialcountResult;
import weixin.popular.bean.media.Media;
import weixin.popular.bean.media.MediaType;
import weixin.popular.bean.media.UploadimgResult;
import weixin.popular.bean.message.Article;

@Service
public class MpUserService extends MpService {
	
	@Autowired
	private WxQrcodeRepository wxQrcodeRepository;
	@Autowired
	private EventService eventService;
	@Autowired
	private CardService cardService;
	@Autowired
	private PayService payService;
	@Autowired
	private MaterialService materialService;
	
	/**
	 * 长链接转短链接
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public String longUrl2ShortUrl(String url) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		WxMpService wxMpService = wxMpService(configBean);
		String shortUrl = wxMpService.shortUrl(url);
		return JSON.toJSONString(Result.ok(shortUrl));
	}

	/**
	 * 消息模板删除
	 * @param templateId
	 * @return
	 * @throws Exception
	 */
	public String templateDelete(String templateId) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		WxMpTemplateMsgService wxMpTemplateMsgService = new WxMpTemplateMsgServiceImpl(wxMpService(configBean));
		wxMpTemplateMsgService.delPrivateTemplate(templateId);
		return JSON.toJSONString(Result.ok());
	}
	
	/**
	 * 网页jsapi签名获取
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public String getJsapiSignature(String url) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		WxMpService wxMpService = wxMpService(configBean);
		WxJsapiSignature jsapiSignature = wxMpService.createJsapiSignature(url);
		return JSON.toJSONString(Result.ok(jsapiSignature));
	}

	/**
	 * 给用户下发模板消息
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public String templateSend(String data) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		WxMpTemplateMessage templateMessage = JSON.parseObject(data, WxMpTemplateMessage.class);
		if(StringUtils.isEmpty(configBean.getOpenid()) && StringUtils.isEmpty(templateMessage.getToUser())) {
			
			return JSON.toJSONString(Result.error("模板消息接收人openid不能为空"));
		}	
		if(!StringUtils.isEmpty(configBean.getOpenid())) {
			templateMessage.setToUser(configBean.getOpenid());
		}
		WxMpTemplateMsgService wxMpTemplateMsgService = new WxMpTemplateMsgServiceImpl(wxMpService(configBean));
		String msg = wxMpTemplateMsgService.sendTemplateMsg(templateMessage);
		return JSON.toJSONString(Result.ok(msg));
	}

	/**
	 * 公众号二维码生成
	 * @param sceneId
	 * @param sceneStr
	 * @param expireSeconds
	 * @param qrcodeType TEMP:临时二维码，FOREVER:永久二维码
	 * @return
	 * @throws Exception
	 */
	public String qrcode(Integer sceneId, String sceneStr, Integer expireSeconds, String qrcodeType) throws Exception{
		//临时二维码，默认有效时间180s
		if(qrcodeType.equals("TEMP")) return qrcodeTemp(sceneId, sceneStr, expireSeconds);
		//永久二维码
		if(qrcodeType.equals("FOREVER")) return qrcodeUnlimit(sceneId, sceneStr);
		return JSON.toJSONString(Result.ok());
	}

	/**
	 * 微信管理后台填写网页授权/业务域名时需要校验.txt文件，通过该服务即可校验
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public String domainVertify(String fileName) throws Exception{
		String[] fileNames = fileName.split("(_)|(\\.)");
		if(fileNames[fileNames.length-1].equals("txt")) {
			
			return fileNames[fileNames.length-2];
		}
		
		return fileNames[fileNames.length-1];
	}

	/**
	 * 微信登录授权回调
	 * @param code
	 * @param redirect_uri
	 * @throws Exception
	 */
	public void authCallBack(String code, String redirect_uri) throws Exception{
		HttpServletResponse response = getResponse();
		response.setCharacterEncoding("UTF-8");		
		if(redirect_uri == null || "".equals(redirect_uri)) {
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println("redirect_uri参数错误，参数为空");
			return;
		}
		redirect_uri = new String(URLCodec.decodeUrl(redirect_uri.getBytes("UTF-8")));
		logger.info("解码后的参数redirect_uri={}",redirect_uri);
		StringBuilder redirectUri = new StringBuilder(redirect_uri);
		if(redirect_uri.contains("?")) {
			redirectUri.append("&code=").append(code);
		}else {
			redirectUri.append("?code=").append(code);
		}
		logger.info("拼接code后的重定向地址redirectUri={}",redirectUri);
		response.sendRedirect(redirectUri.toString());
	}
	
	/**
	 * 网页登录授权url获取
	 * @param redirectUri
	 * @return
	 * @throws Exception
	 */
	public String buildAuthorizationUrl(String redirectUri) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		// 获取请求域名
		String requestUrl = host();
		String redirect_uri = requestUrl + "/wxapi/mp/oauth2/authCallBack?redirect_uri="
		+host()+"/uaa/login/callback/console-mp?redirect_url="+redirectUri;//request.getContextPath()
		WxMpService wxMpService = wxMpService(configBean);
		String url = wxMpService.oauth2buildAuthorizationUrl(redirect_uri, "snsapi_userinfo", "");
		return JSON.toJSONString(Result.ok(url));
	}

	/**
	 * 获取当前公众号下的所有模板消息
	 * @return
	 * @throws Exception
	 */
	public String templates() throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		WxMpTemplateMsgService wxMpTemplateMsgService = new WxMpTemplateMsgServiceImpl(wxMpService(configBean));
		List<WxMpTemplate> templates = wxMpTemplateMsgService.getAllPrivateTemplate();
		return JSON.toJSONString(Result.ok(templates));
	}

	public String menuDelete(String group) throws Exception{
		BaseConfigBean configBean = getBaseConfig(group);
		WxMpMenuService wxMpMenuService = new WxMpMenuServiceImpl(wxMpService(configBean));
		wxMpMenuService.menuDelete();
		return JSON.toJSONString(Result.ok());
	}

	public String getMenus(String group) throws Exception{
		BaseConfigBean configBean = getBaseConfig(group);
		WxMpMenuService wxMpMenuService = new WxMpMenuServiceImpl(wxMpService(configBean));
		WxMpGetSelfMenuInfoResult menuInfo = wxMpMenuService.getSelfMenuInfo();
		return JSON.toJSONString(Result.ok(menuInfo.getSelfMenuInfo().getButtons()));
	}

	public String menuCreate(String data) throws Exception{
		JSONObject jsonObject = JSON.parseObject(data);
		BaseConfigBean configBean = getBaseConfig(jsonObject.getString("group"));
		WxMpMenuService wxMpMenuService = new WxMpMenuServiceImpl(wxMpService(configBean));
		WxMenu wxMenu = JSON.parseObject(data, WxMenu.class);
		wxMpMenuService.menuCreate(wxMenu);
		return JSON.toJSONString(Result.ok());
	}

	/**
	 * 根据openid获取用户信息
	 * @param openid
	 * @return
	 * @throws Exception
	 */
	public String getUserInfoByOpenid(String openid) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		String oid = "";
		if(StringUtils.isEmpty(configBean.getOpenid()) && "openid".equals(openid)) {
			
			return JSON.toJSONString(Result.error("openid不能为空！"));
		}else {
			if(StringUtils.isNotEmpty(configBean.getOpenid())) {
				oid = configBean.getOpenid();
			}else {
				oid = openid;
			}
		}
		WxMpService wxMpService = wxMpService(configBean);
		WxMpUserService wxMpUserService = new WxMpUserServiceImpl(wxMpService);
		WxMpUser userInfo = wxMpUserService.userInfo(oid);
		return JSON.toJSONString(Result.ok(userInfo));
	}

	/**
	 * 给指定openid的用户发送客服消息
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public String sendMessage(String data) throws Exception{
		WxMpKefuMessage message = JSON.parseObject(data, WxMpKefuMessage.class);
		BaseConfigBean configBean = getBaseConfig("");
		if(StringUtils.isEmpty(configBean.getOpenid()) && StringUtils.isEmpty(message.getToUser())) {
			
			return JSON.toJSONString(Result.error("客服消息接收人openid不能为空！"));
		}
		WxMpKefuService wxMpKefuService = new WxMpKefuServiceImpl(wxMpService(configBean));
		if(StringUtils.isEmpty(message.getToUser())) {
			message.setToUser(configBean.getOpenid());
		}
		wxMpKefuService.sendKefuMessage(message);
		return JSON.toJSONString(Result.ok());
	}
	
	/**
	 * 临时二维码生成
	 * @param sceneId
	 * @param sceneStr
	 * @param expireSeconds
	 * @return
	 * @throws Exception
	 */
	public String qrcodeTemp(Integer sceneId, String sceneStr, Integer expireSeconds) throws Exception{
		if("-1".equals(sceneStr) && sceneId==-1) {
			
			return JSON.toJSONString(Result.ok("senceStr,senceId必须有一个不为空值！"));
		}
		BaseConfigBean configBean = getBaseConfig("");
		WxMpQrcodeService wxMpQrcodeService= new WxMpQrcodeServiceImpl(wxMpService(configBean));
		WxMpQrCodeTicket wxMpQrCodeTicket = null;
		if("-1".equals(sceneStr)) {
			wxMpQrCodeTicket = wxMpQrcodeService.qrCodeCreateTmpTicket(sceneStr, expireSeconds);
		}else {
			wxMpQrCodeTicket = wxMpQrcodeService.qrCodeCreateTmpTicket(sceneId, expireSeconds);
		}
		return JSON.toJSONString(Result.ok(wxMpQrCodeTicket));
	}
	
	/**
	 * 永久二维码生成
	 * @param sceneId
	 * @param sceneStr
	 * @return
	 * @throws Exception
	 */
	public String qrcodeUnlimit(Integer sceneId, String sceneStr) throws Exception{
		if("-1".equals(sceneStr) && sceneId==-1) {
			return JSON.toJSONString(Result.error("senceStr,senceId必须有一个不为空值！"));
		}
		BaseConfigBean baseConfigBean = getBaseConfig("");
		WxMpQrCodeTicket wxMpQrCodeTicket = null;
		WxQrcode wxQrcode = wxQrcodeRepository.queryTopEntityByCodeEqualsAndAppidEquals(sceneStr, baseConfigBean.getAppid());
		if(wxQrcode == null) {
			wxQrcode = wxQrcodeRepository.queryTopEntityByCodeEqualsAndAppidEquals(String.valueOf(sceneId), baseConfigBean.getAppid());
		}
		if(wxQrcode == null) {//长久二维码需要做存储
			logger.info("数据库没有存储该二维码");
			WxMpQrcodeService wxMpQrcodeService = new WxMpQrcodeServiceImpl(wxMpService(baseConfigBean));
			if("-1".equals(sceneStr)) {
				wxMpQrCodeTicket = wxMpQrcodeService.qrCodeCreateLastTicket(sceneStr);
				saveQrcode(wxMpQrCodeTicket, sceneStr, baseConfigBean.getAppid());
			}else {
				wxMpQrCodeTicket = wxMpQrcodeService.qrCodeCreateLastTicket(sceneId);
				saveQrcode(wxMpQrCodeTicket, String.valueOf(sceneId), baseConfigBean.getAppid());
			}
			saveQrcode(wxMpQrCodeTicket, sceneStr, baseConfigBean.getAppid());
		}else {//长久二维码，已经生成过该二维码，直接返回即可
			logger.info("数据库已存储该二维码");
			wxMpQrCodeTicket = new WxMpQrCodeTicket();
			wxMpQrCodeTicket.setTicket(wxQrcode.getTicket());
			wxMpQrCodeTicket.setUrl(wxQrcode.getQrcodeUrl());
		}
		return JSON.toJSONString(Result.ok(wxMpQrCodeTicket));
	}
	
	/**
	 * 二维码信息持久化存储
	 * @param wxMpQrCodeTicket
	 * @param code
	 * @param appid
	 */
	public void saveQrcode(WxMpQrCodeTicket wxMpQrCodeTicket,String code,String appid) {
		WxQrcode wxQrcode = new WxQrcode();
		wxQrcode.setAppid(appid);
		wxQrcode.setCode(code);
		wxQrcode.setCreateTime(new Date());
		wxQrcode.setQrcodeUrl(wxMpQrCodeTicket.getUrl());
		wxQrcode.setTicket(wxMpQrCodeTicket.getTicket());
		wxQrcodeRepository.save(wxQrcode);
	}
	
	/**
	 * 微信消息推送事件
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public String wxeventPost(String data) throws Exception{
		BaseConfigBean baseConfigBean = getRequestParams();
		Long start = System.currentTimeMillis();
		//签名校验，校验请求是否来自微信服务器
		if(!baseConfigBean.isWxOffical()) {
			
			return "非法请求";
		}
		String result = eventService.eventService(baseConfigBean, data);
		Long end = System.currentTimeMillis();
		logger.info("【请求时间】:{}ms",end-start);
		return result;
	}
	
	
	public String wxeventGet() throws Exception{
		BaseConfigBean configBean = getRequestParams();
		String result = "";
		if(!configBean.isWxOffical()) {
			return "非法请求";
		}
		
		if(StringUtils.isNotBlank(configBean.getEchostr())) {
			result = configBean.getEchostr();
		}
		return result;
	}
	
	/**
	 * 事件请求参数获取
	 * @param request
	 * @return
	 */
	public BaseConfigBean getRequestParams() {
		HttpServletRequest request = getRequest();
		BaseConfigBean baseConfigBean = getBaseConfig("");
		baseConfigBean.setEchostr(request.getParameter("echostr"));
		baseConfigBean.setEncrypt_type(request.getParameter("encrypt_type"));
		baseConfigBean.setMsg_signature(request.getParameter("msg_signature"));
		baseConfigBean.setNonce(request.getParameter("nonce"));
		baseConfigBean.setSignature(request.getParameter("signature"));
		baseConfigBean.setTimestamp(request.getParameter("timestamp"));
		logger.info("微信推送事件请求参数===============baseConfigBean===============\n{}",JSON.toJSONString(baseConfigBean));
		return baseConfigBean;
	}
	
	/**
	 * 卡券创建
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public String createCard(String data) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		Result<?> result = cardService.cardCreate(data, getAccessToken(configBean.getAppid(), configBean.getAppsecret()));
		return JSON.toJSONString(result);
	}
	
	/**
	 * 卡券签名
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public String createSignature(String data) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		WxCardApiSignature wxCardApiSignature = cardService.signature(data, configBean);
		return JSON.toJSONString(Result.ok(wxCardApiSignature));
	}

	public String consumeCard(String data) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		return cardService.consumeCard(data, configBean);
	}

	public String decryptCode(String encryptCode) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		String reString = cardService.decryptCode(encryptCode, configBean);
		return JSON.toJSONString(Result.ok(reString));
	}

	public String cardCodeQuery(String code, String cardId) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		Result<?> result = cardService.queryCardCode(cardId, code, configBean);
		return JSON.toJSONString(result);
	}

	public String cardDetail(String cardId) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		String result = cardService.getCardDetail(cardId, getAccessToken(configBean.getAppid(), configBean.getAppsecret()));
		return JSON.toJSONString(Result.ok(result));
	}
	
	public String cardDelete(String cardId) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		cardService.cardDelete(cardId, getAccessToken(configBean.getAppid(), configBean.getAppsecret()));
		return JSON.toJSONString(Result.ok());
	}

	/**
	 * 红包查询
	 * @param commondCode
	 * @param mchBillNo
	 * @return
	 * @throws Exception
	 */
	public String redpackGet(String commondCode, String mchBillNo) throws Exception{
		if("-1".equals(commondCode)) commondCode = "";
		if("-1".equals(mchBillNo)) mchBillNo = "";
		if(StringUtils.isEmpty(mchBillNo) && StringUtils.isEmpty(commondCode)) {
			
			return JSON.toJSONString(Result.ok(null),SerializerFeature.WriteNullStringAsEmpty);
		}
		WxPayConfig wxPayConfig = getPayConfig(false);
		Result<?> result = payService.redpackGet(commondCode, mchBillNo, wxPayConfig);
		return JSON.toJSONString(result);
	}

	/**
	 * 红包发送（普通红包/裂变红包）
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public String redpackSend(String data) throws Exception{
		WxPayConfig wxPayConfig = getPayConfig(true);
		wxPayConfig.setNotifyUrl(host()+Constants.MP_DEFUALT_NOFITY_HOST);
		WxPaySendRedpackResult redpackResult = payService.redpack(data, wxPayConfig);
		return JSON.toJSONString(Result.ok(redpackResult));
	}

	public String payNotify(String data) throws Exception{
		WxPayConfig wxPayConfig = getPayConfig(false);
		BaseConfigBean configBean = getBaseConfig("");
		return payService.payNotify(data, wxPayConfig, configBean);
	}

	public String refundNotify(String data) throws Exception{
		WxPayConfig wxPayConfig = getPayConfig(false);
		BaseConfigBean configBean = getBaseConfig("");
		return payService.refundNotify(data, wxPayConfig, configBean);
	}

	public String unifiedOrder(String orderData) throws Exception{
		WxPayConfig wxPayConfig = getPayConfig(false);
		return payService.unifiedOrder(orderData, wxPayConfig);
	}

	public String refund(String refundData) throws Exception{
		WxPayConfig wxPayConfig = getPayConfig(true);
		return payService.refund(wxPayConfig, refundData);
	}

	public String refundQuery(String outTradeNo, String transactionId, String outRefundNo, String refundId) throws Exception{
		WxPayConfig wxPayConfig = getPayConfig(false);
		if("-1".equals(outTradeNo)) outTradeNo = "";
		if("-1".equals(transactionId)) transactionId = "";
		if("-1".equals(outRefundNo)) outRefundNo = "";
		if("-1".equals(refundId)) refundId = "";
		return payService.refundQuery(wxPayConfig, transactionId, outTradeNo, outRefundNo, refundId);
	}

	public String closeOrder(String outTradeNo) throws Exception{
		WxPayConfig wxPayConfig = getPayConfig(false);
		return payService.orderClose(wxPayConfig, outTradeNo);
	}

	public String queryEntPay(String partnerTradeNo) throws Exception{
		WxPayConfig wxPayConfig = getPayConfig(false);
		return payService.queryEntPay(wxPayConfig, partnerTradeNo);
	}

	public String downloadBill(String billDate, String billType, String tarType, String deviceInfo) throws Exception{
		WxPayConfig wxPayConfig = getPayConfig(false);
		if("-1".equals(deviceInfo)) deviceInfo = "";
		return payService.dowloadBill(wxPayConfig, billDate, billType, tarType, deviceInfo);
	}

	public String entPay(String data) throws Exception{
		WxPayConfig wxPayConfig = getPayConfig(true);
		wxPayConfig.setNotifyUrl(host()+Constants.MP_DEFUALT_NOFITY_HOST);
		return payService.entPay(wxPayConfig, data);
	}

	public String entPayBank(String data) throws Exception{
		WxPayConfig wxPayConfig = getPayConfig(true);
		wxPayConfig.setNotifyUrl(host()+Constants.MP_DEFUALT_NOFITY_HOST);
		return payService.payBank(wxPayConfig, data);
	}

	public String queryEntPayBank(String partnerTradeNo) throws Exception{
		WxPayConfig wxPayConfig = getPayConfig(false);
		return payService.queryEntPay(wxPayConfig, partnerTradeNo);
	}

	public String queryOrder(String outTradeNo, String transactionId) throws Exception{
		if("-1".equals(outTradeNo)) outTradeNo = "";
		if("-1".equals(transactionId)) transactionId = "";
		WxPayConfig wxPayConfig = getPayConfig(false);
		return payService.orderQuery(wxPayConfig, outTradeNo, transactionId);
	}

	public String addMaterial(MaterialVo materialVo) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		String accessToken = getAccessToken(configBean.getAppid(), configBean.getAppsecret());
		String downloadURL = StorageServiceUtils.getDownloadURL(host(), StorageServiceUtils.getStoreFileName(materialVo.getStoreFileName()));
		Description description = new Description(materialVo.getTitle(), materialVo.getIntroduction());
		MediaType mediaType = null;
		switch (materialVo.getMaterialType()) {
			case "image":
				mediaType = MediaType.image;
				break;
			case "voice-mp3":
				mediaType = MediaType.voice_mp3;
				break;
			case "voice-arm":
				mediaType = MediaType.voice_arm;
				break;
			case "video":
				mediaType = MediaType.video;
				break;
			case "thumb":
				mediaType = MediaType.thumb;
				break;
			default:
				break;
		}
		Media material = MaterialAPI.add_material(accessToken, mediaType, StorageServiceUtils.getFileInputStream(downloadURL), description);
		return JSON.toJSONString(Result.ok(material));
	}
	
	public String addNewsMaterial(String data) throws Exception{
		List<Article> articles = JSON.parseArray(data, Article.class);
		BaseConfigBean configBean = getBaseConfig("");
		String accessToken = getAccessToken(configBean.getAppid(), configBean.getAppsecret());
		Media news = MaterialAPI.add_news(accessToken, articles);
		return JSON.toJSONString(Result.ok(news));
	}

	public String delMaterial(String mediaId) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		String accessToken = getAccessToken(configBean.getAppid(), configBean.getAppsecret());
		BaseResult baseResult = MaterialAPI.del_material(accessToken, mediaId);
		if("ok".equals(baseResult.getErrcode())) {
			return JSON.toJSONString(Result.ok());
		}
		return JSON.toJSONString(Result.error(baseResult.getErrmsg()));
	}

	public String updateMaterial(String mediaId, Integer index, String data) throws Exception{
		BaseConfigBean baseConfig = getBaseConfig("");
		String accessToken = getAccessToken(baseConfig.getAppid(), baseConfig.getAppsecret());
		Article article = JSON.parseObject(data, Article.class);
		List<Article> articles = new ArrayList<Article>();
		articles.add(article);
		BaseResult baseResult = MaterialAPI.update_news(accessToken, mediaId, index, articles);
		if("ok".equals(baseResult.getErrcode())) {
			return JSON.toJSONString(Result.ok());
		}
		return JSON.toJSONString(Result.error(baseResult.getErrmsg()));
	}

	public String getMaterial(String mediaId) throws Exception{
		BaseConfigBean baseConfig = getBaseConfig("");
		String accessToken = getAccessToken(baseConfig.getAppid(), baseConfig.getAppsecret());
		MaterialGetResult material = MaterialAPI.get_material(accessToken, mediaId);
		return JSON.toJSONString(Result.ok(material));
	}

	public String materialCount(String group) throws Exception{
		BaseConfigBean baseConfig = getBaseConfig("");
		String accessToken = getAccessToken(baseConfig.getAppid(), baseConfig.getAppsecret());
		MaterialcountResult materialcountResult = MaterialAPI.get_materialcount(accessToken);
		return JSON.toJSONString(Result.ok(materialcountResult));
	}

	public String materialUploadimg(MaterialVo materialVo) throws Exception{
		BaseConfigBean baseConfig = getBaseConfig("");
		String accessToken = getAccessToken(baseConfig.getAppid(), baseConfig.getAppsecret());
		String downloadUrl = StorageServiceUtils.getDownloadURL(host(), StorageServiceUtils.getDownloadURL(host(), materialVo.getStoreFileName()));
		UploadimgResult uploadimg = MediaAPI.mediaUploadimg(accessToken, StorageServiceUtils.getFileInputStream(downloadUrl));
		return JSON.toJSONString(uploadimg.getUrl());
	}

	public String getTempMaterial(String mediaId) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		String accessToken = getAccessToken(configBean.getAppid(), configBean.getAppsecret());
		return materialService.getTempMaterial(mediaId, accessToken);
	}

	public String addTempMaterial(MaterialVo materialVo) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		String accessToken = getAccessToken(configBean.getAppid(), configBean.getAppsecret());
		return materialService.addTempMaterial(materialVo, accessToken);
	}

	public String materials(Integer pageNum, Integer pageSize, String type) throws Exception{
		BaseConfigBean configBean = getBaseConfig("");
		String accessToken = getAccessToken(configBean.getAppid(), configBean.getAppsecret());
		MaterialBatchgetResult materials = MaterialAPI.batchget_material(accessToken, type, (pageNum-1)*pageSize, pageSize);
		return JSON.toJSONString(Result.ok(materials));
	}
	
	public String getOauth2UserInfo(String type, String code, String lang) throws Exception{
		BaseConfigBean configBean = null;
		if("mp".equals(type)) {
			 configBean = getBaseConfig("");
		}else {
			configBean = getBaseConfig(Constants.OPEN_KEY,"default_open");
		}
		WxMpService wxMpService = wxMpService(configBean);
		WxMpOAuth2AccessToken oAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
		WxMpUser mpUser = wxMpService.oauth2getUserInfo(oAuth2AccessToken, lang);
		return JSON.toJSONString(mpUser);
	}
}
